package com.cherrish.demo.collections;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @author cherrish
 * @time 2019-04-09 11:12
 * @name MyArrayList
 * @desc:
 */
public class MyArrayList<T> implements Iterable<T>{
    private T[] theItems;
    private int theSize;
    private static final int DEFAULT_CAPACITY = 10;

    public MyArrayList() {
        this.theSize = 0;

    }

    public void add(T data){
        add(theSize, data);
    }

    public void add(int index, T data){
        if(size() == theItems.length){
            ensureCapacity(size() * 2 + 1);
        }
        for(int i = theSize; i > index; i--){
            theItems[i] = theItems[i - 1];
        }
        theItems[index] = data;
        theSize++;
    }

    public T get(int index){
        if (index < 0 || index >= size()){
            throw new IndexOutOfBoundsException("index out of Bounds");
        }
        return theItems[index];
    }

    public T remove(int index){
        T removeData = get(index);
        for(int i = index; i < (size() - 1); i++){
            theItems[i] = theItems[i + 1];
        }
        theSize--;
        return removeData;
    }

    public int size(){
        return theSize;
    }

    private void ensureCapacity(int newCapacity){
        if(theSize > newCapacity){
            return;
        }
        T[] old = theItems;
        theItems = (T[]) new Object[newCapacity];
        System.arraycopy(old, 0, theItems, 0, old.length);
    }

    @Override
    public Iterator<T> iterator() {
        return null;
    }

    @Override
    public void forEach(Consumer<? super T> action) {

    }

    @Override
    public Spliterator<T> spliterator() {
        return null;
    }
}
